<template>
  <div>
    <FilePreview
      valueField="label"
      :isDownload="false"
      :file="fileObj"
      downloadField="value"
      @register="registerModal"
      @preview-file="previewFn"
      :api-fn="jdFileDown"
      :downloadFileParam="downloadFileParam"
      @cancel="change"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, createVNode, onDeactivated, nextTick } from 'vue';
  import { useModal } from '/@/components/Modal';
  import FilePreview from '/@/components/Upload/src/HUpload/src/components/previewModal.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { jdFileDown, generateFile } from '/@/api/jd/water-box';

  const props = defineProps({
    allData: {
      type: Object,
      default: () => {},
    },
    record: {
      type: Object,
      default: () => {},
    },
  });
  interface DownLoadParam {
    path: string;
  }

  const downloadFileParam = ref<DownLoadParam>({ path: '' });

  const { createMessage } = useMessage();
  interface FileParam {
    label: string;
    value: string;
  }
  //  base64转url
  function decode(str) {
    // 过程：从字节流到百分比编码，再到原始字符串
    return decodeURIComponent(
      atob(str)
        .split('')
        .map(function (c) {
          return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        })
        .join(''),
    );
  }

  const fileObj = ref<FileParam>({ label: '', value: '' });

  const emit = defineEmits(['change']);

  const [registerModal, { openModal }] = useModal();

  const change = (data) => {
    emit('change', data);
  };

  // 预览
  let previewFn = (val) => {
    console.log(123);

    const valueFiled = props.allData.btnItem.dynamicParams;

    if (!valueFiled) {
      createMessage.warn('请配置按钮的预览文件的动态入参取值！');
      return;
    }

    const value = props.allData.data[valueFiled];

    if (!value) {
      Modal.warning({
        title: '记录单生成中',
        icon: createVNode(ExclamationCircleOutlined),
        content: '当前记录单正在生成中',
        okText: '确定',
        async onOk() {
          await generateFile(props.record.water_meter_id);
          props.allData.btnItem.tabFn.reload();
          change(false);
        },

        // onCancel() {
        //   console.log('Cancel');
        //   change(false);
        // },
      });
      return;
    }
    downloadFileParam.value.path = decode(value);
    fileObj.value = {
      label: value,
      value,
    };
    val(fileObj.value);
    nextTick(() => {
      openModal(true);
    });
  };

  onDeactivated(() => {
    Modal.destroyAll();
  });
</script>

<style lang="less" scoped></style>
